package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.redisconfig.RedissonAutoConfiguration;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.shopping.constants.ShoppingRetCode;
import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.form.CartRequest;
import com.cskaoyan.shopping.form.CheckAllItemRequest;
import com.cskaoyan.shopping.service.ICartService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author : gao
 * @since: 2022/10/25  20:28
 */
@Service
@Slf4j
public class ICartServiceImpl implements ICartService {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    CartItemConverter cartItemConverter;

    /**
     * @Description:获得购物车列表
     * @author chengyi
     * @date 2022/10/26 17:08
     */
    @Override
    public List<CartProductDto> getCartListById(Long userId) {
        //获取该用户的购物车数据
        String id = userId.toString();
        Map<String, CartProductDto> cartMap = redissonClient.getMap(id);
        //创建List
        List<CartProductDto> list = new ArrayList<>();
        //对List赋值
        for (String s : cartMap.keySet()) {
            CartProductDto cartProductDto = cartMap.get(s);
            list.add(cartProductDto);
        }

        return list;
    }


    /**
     * @Author Yi
     * @Description 加入购物车
     */
    @Override
    public void addToCart(CartRequest request) {

        // 传来的参数
        String userId = request.getUserId().toString();
        String productId = request.getProductId().toString();
        long productNum = Long.parseLong(request.getProductNum().toString());

        // 测试用
        // String userId = "233";
        // String productId = "100026701";
        // Long productNum = 2L;


        // 如果数据库里没有这个userId呢？那应该新建一条，但是不知道怎么新建。
        // 2022年10月27日 10:02:48：会自动新建的
        Map<String, CartProductDto> cartMap = redissonClient.getMap(userId);

        if (!cartMap.containsKey(productId)) {
            // 创建CartProductDto实例
            Item item = itemMapper.selectByPrimaryKey(productId);
            CartProductDto cartProductDto = cartItemConverter.item2Dto(item);
            cartProductDto.setProductNum(productNum);
            cartProductDto.setChecked("true");

            cartMap.put(productId, cartProductDto);
        } else {
            CartProductDto cartProductDto = cartMap.get(productId);
            Long productNumBefore = cartProductDto.getProductNum();
            cartProductDto.setProductNum(productNumBefore + productNum);

            cartMap.put(productId, cartProductDto);
        }

    }

    /**
     * @Author Yi
     * @Description 更新购物车
     * @Date 2022/10/26 16:57
     */
    @Override
    public void updateCartNum(CartRequest request) {
        String userId = request.getUserId().toString();
        String productId = request.getProductId().toString();
        long productNum = Long.parseLong(request.getProductNum().toString());
        String checked = request.getChecked();

        Map<String, CartProductDto> cartMap = redissonClient.getMap(userId);

        // 更改勾选状态和数目
        CartProductDto cartProductDto = cartMap.get(productId);
        cartProductDto.setProductNum(productNum);
        cartProductDto.setChecked(checked);

        // 更新数据库
        cartMap.put(productId, cartProductDto);

    }


    @Override
    public void checkAllCartItem(CheckAllItemRequest request) {
        Long userId = request.getUserId();
        String checked = request.getChecked();
        Map<String, CartProductDto> cartMap = null;

        try {
            cartMap = redissonClient.getMap(userId.toString());
            Set<Map.Entry<String, CartProductDto>> entries = cartMap.entrySet();
            for (Map.Entry<String, CartProductDto> entry : entries) {
                CartProductDto cartProductDto = entry.getValue();
                cartProductDto.setChecked(checked);
                entry.setValue(cartProductDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException(ShoppingRetCode.DB_EXCEPTION.getCode(),
                    ShoppingRetCode.DB_EXCEPTION.getMessage());
        }

    }

    /**
     * 删除购物车中的商品
     *
     * @return {@link null}
     * @author gao
     * @since 2022/10/26 9:51
     */

    @Override
    public void deleteCartItem(Long uid, Long itemId) {
        //获取该用户的商品
        Map<String, CartProductDto> cartMap = redissonClient.getMap(uid.toString());
        CartProductDto cartProductDto = cartMap.get(itemId.toString());
        if (cartProductDto == null) {
            //如果商品不存在抛出异常
            throw new BizException(ShoppingRetCode.CART_PRODUCT_NOT_EXISTS.getCode(),
                    ShoppingRetCode.CART_PRODUCT_NOT_EXISTS.getMessage());
        }
        //删除商品
        try {
            cartMap.remove(itemId.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException(ShoppingRetCode.DB_EXCEPTION.getCode(),
                    ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        log.info("用户{}的购物车中的{}商品已被删除", uid, itemId);
    }

    /**
     * 删除选中的商品
     *
     * @return {@link null}
     * @author gao
     * @since 2022/10/26 10:57
     */
    @Override
    public void deleteCheckedItem(Long userId) {
        Map<String, CartProductDto> cartMap = redissonClient.getMap(userId.toString());
        Set<Map.Entry<String, CartProductDto>> entrySet = cartMap.entrySet();

        //遍历所有购物车的商品
        try {
            for (Map.Entry<String, CartProductDto> cartProduct : entrySet) {
                CartProductDto product = cartProduct.getValue();
                if (product.getChecked().equals("true")) {
                    //删除选中的商品
                    cartMap.remove(cartProduct.getKey());
                    log.info("用户{}的购物车中的{}商品已被删除", userId, cartProduct.getKey());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException(ShoppingRetCode.DB_EXCEPTION.getCode(),
                    ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
    }

    @Override
    public void deleteCartItemOfOrder(ClearCartItemRequest request) {
        Map<Object, Object> map = redissonClient.getMap(request.getUserId().toString());
        @NotEmpty List<Long> productIds = request.getProductIds();
        try {
            for (Long productId : productIds) {
                map.remove(productId.toString());
                log.info("用户{}的购物车中的{}商品已被删除", request.getUserId(), productId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException(ShoppingRetCode.CART_PRODUCT_NOT_EXISTS.getCode(),
                    ShoppingRetCode.CART_PRODUCT_NOT_EXISTS.getMessage());
        }
    }
}
